import java.util.Arrays;


public class RotateMatrix {
    public static void main(String[] args) {
        int[][] test= {{1,2,3},{4,5,6},{7,8,9}};
        int[][] test2 =
                {  {5, 1, 9,11},
                        { 2, 4, 8,10},
        {13, 3, 6, 7},
            {15,14,12,16}}
        ;
        rotate2(test);
        rotate2(test2);
        printArray(test);
        printArray(test2);
    }

    private static void printArray(int[][] test) {
        System.out.println("start");
        for (int i = 0; i < test.length; i++) {
            for (int j = 0; j < test[i].length; j++) {
                System.out.print(test[i][j]);
                System.out.print(" ");
            }
            System.out.println();
        }
        System.out.println("end");
    }

    /**
     * 先转置
     * 在对称交换
     * @param matrix
     */
    public static void rotate(int[][] matrix){
        for (int i = 0; i < matrix.length; i++) {
            for (int j = i; j < matrix[i].length; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length/2; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][matrix.length-1-j];
                matrix[i][matrix.length-1-j] = temp;
            }
        }
        int i =0;
        System.out.printf("", i);
    }

    public static void rotate2(int[][] matrix) {
        int n = matrix.length;

        for (int i = 0; i < n / 2 + n % 2; i++) {
            for (int j = 0; j < n / 2; j++) {
                int[] tmp = new int[4];
                int row = i;
                int col = j;
                for (int k = 0; k < 4; k++) {
                    tmp[k] = matrix[row][col];
                    // 定位下一个数
                    int x = row;
                    row = col;
                    col = n - 1 - x;
                }

                for (int k = 0; k < 4; k++) {
                    matrix[row][col] = tmp[(k + 3) % 4];
                    int x = row;
                    row = col;
                    col = n - 1 - x;
                }
            }
        }
    }

    public void rotate3(int[][] matrix) {
        int n = matrix.length;

        // 不区分子矩阵，直接遍历每一个元素
        for( int i = 0; i < (n + 1)/2; i++ ){
            for( int j = 0; j < n/2; j++ ){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n-j-1][i];
                matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
                matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
                matrix[j][n-i-1] = temp;
            }
        }
    }

}
